package com.link.base.tencent.thirdclient.wechat.service;

import com.alibaba.fastjson.JSONObject;
import com.link.base.base.user.model.User;
import com.link.base.base.user.service.UserService;
import com.link.core.cllog.LCLogger;
import com.link.base.tencent.thirdclient.wechat.model.WxLogin;
import com.link.core.basic.service.ServiceException;
import com.link.core.util.HttpRequestUtil;
import com.link.core.util.RedisUtil;
import com.link.core.util.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

/**
 * 微信登录服务实现
 *
 * @author LiQun
 * @date 2018/2/28 11:13
 * update by ouyangzhenqiang at 2018/04/16
 */
@Service
public class WxLoginServiceImpl implements WxLoginService {

    private static final String APP_ENTRANCE = "app";

    @Resource
    private UserService userService;

    @Override
    public WxLogin getWeChatInfo(WxLogin wxLogin) throws Exception {
        String appId = wxLogin.getAppId();
        // 微信验证临时票据
        String code = wxLogin.getCode();
        String uuid = wxLogin.getUuid();
        if (StringUtils.isNotBlank(appId) && StringUtils.isNotBlank(code) && StringUtils.isNotBlank(uuid)) {
            //  获取appId/appSecret
            Map<String, String> appInfo = getAppInfo(appId);
            String weixinAppId = appInfo != null ? appInfo.get("weixinAppId") : null;
            String weixinAppSecret = appInfo != null ? appInfo.get("weixinAppSecret") : null;
            if (weixinAppId == null || weixinAppSecret == null) {
                throw new ServiceException("THIRDWX-001");
            }

            Map<String, String> tokenMap = getTokenInfo(weixinAppId, weixinAppSecret, code);
            // 获取unionId
            String unionId = tokenMap.get("unionId");
            User user = new User();
            user.setWxUnionId(unionId);
            // 根据unionId查询客户是否存在
            user = userService.getBoundAccounts(user);
            LCLogger.info().withMessageKey("getWeChatInfo").withMessage("根据unionId => " + unionId + "查询用户是否存在").flush();

            if (user == null) {
                LCLogger.info().withMessageKey("getWeChatInfo").withMessage(unionId + "未绑定用户").flush();
                wxLogin.setBindUser(false);
                wxLogin.setUnionId(unionId);
            } else {
                LCLogger.info().withMessageKey("getWeChatInfo").withMessage(unionId + "已绑定用户").flush();
                wxLogin.setBindUser(true);
                wxLogin.setUnionId(unionId);
                wxLogin.setLogin(user.getLogin());
                // 已绑定的情况下，默认其为重新登录登录操作，后台生成loginToken给前端
                String loginToken = userService.mobileGetLoginToken(user.getLogin(), user.getCorpid(), uuid, null, APP_ENTRANCE);
                wxLogin.setLoginToken(loginToken);
            }
        } else {
            throw new ServiceException("THIRDWX-002");
        }

        return wxLogin;
    }

    @Override
    public Map<String, String> getAppInfo(String appId) throws Exception {
        Map<String, String> result = new HashMap<>();
        LCLogger.info().withMessageKey("getAppInfo").withMessage("获取微信相关信息，应用appId->" + appId).flush();
        String appSecretKey = "wechat_appSecret_" + appId;
        String appIdKey = "wechat_appId_" + appId;

        Long corpId = 0L;
        String weixinAppSecret = RedisUtil.getCropProperty(appSecretKey, corpId.toString());
        String weixinAppId = RedisUtil.getCropProperty(appIdKey, corpId.toString());
        LCLogger.info().withMessageKey("getAppInfo").withMessage("微信 appId->" + weixinAppId + ",appSecret->" + weixinAppSecret).flush();

        result.put("weixinAppId", weixinAppId);
        result.put("weixinAppSecret", weixinAppSecret);
        return result;
    }

    @Override
    public Map<String, String> getTokenInfo(String weixinAppId, String weixinAppSecret, String code) throws Exception {
        Map<String, String> tokenMap = new HashMap<>();
        String url = "https://api.weixin.qq.com/sns/oauth2/access_token";
        String param = "appid=" + weixinAppId + "&secret=" + weixinAppSecret
                + "&code=" + code + "&grant_type=authorization_code";
        String accessTokenJson = HttpRequestUtil.sendGet(url, param);
        LCLogger.info().withMessageKey("getTokenInfo").withMessage("请求微信服务器获取accessToken及refreshToken，返回结果->" + accessTokenJson).flush();
        JSONObject accessTokenObj = JSONObject.parseObject(accessTokenJson);
        tokenMap.put("unionId", accessTokenObj.getString("unionid"));

        return tokenMap;
    }
}
